var apps = getApp();
var basic = require('./basic.js');
var mod = require('./module.js');

/*************************/
/*****自写API方法集成******/
/*************************/
/*
*封装页面跳转API 
*url为跳转目标页，types为跳转方式，data为所页面传递数据（可选，对象方式）
*types取值范围：n-uni.navigateTo;d-uni.redirectTo;s-uni.switchTab;
*ln-n方式的扩展，可以自动判断是否需要登录才能跳转，ld功能相同
*/
function getNav(url) {
  if(url.mode == 2){
    uni.navigateTo({
      url:url.path
    })
  }else if(url.mode == 3){
    uni.switchTab({
      url:url.path
    })
  }else if(url.mode == 4){
    uni.navigateToMiniProgram({
      appId: url.path,
      path: '',
      extraData: {
        
      },
      success(res) {
        // 打开成功
      },
      
    })
  }else if(url.mode == 5){
    uni.navigateTo({
      url:'/pages/Webview/index?path='+url.path
    })
  }else if(url.mode == 6){
	uni.reLaunch({
	  url:url.path
	})
  }else if(url.mode == -1){
    uni.showToast({
        title: '正在开发中...',
        icon :'error',
        duration: 2000
    });
  }
}
/*
*封装页面跳转API
*url为跳转目标页，types为跳转方式，data为所页面传递数据（可选，对象方式）
*types取值范围：n-uni.navigateTo;d-uni.redirectTo;s-uni.switchTab;
*ln-n方式的扩展，可以自动判断是否需要登录才能跳转，ld功能相同
*/
function nav(url, types, data) {
  data = data || '';
  if (data == '') {
    //不带参数的跳转
    if (types == 'n') {
      uni.navigateTo({
        url: url
      })
    } else if (types == 'ln'){
		console.log(apps.globalData.openUserInfo)
		//先验证是否登录
		if(apps.globalData.openUserInfo){
			//已经登录，直接跳转
			uni.navigateTo({
			  url: url
			})
		}else{
			if(apps.globalData.appPlat == 'APP-PLUS' || apps.globalData.appPlat == 'H5'){
				//APP平台，跳转到登录页面
				uni.navigateTo({
					url: '/pages/Component/Module/Login/loginsms/login'
				});
			}else{
				//其他平台，直接跳转
				uni.navigateTo({
				  url: url
				})
			}
		}
	} else if (types == 'd') {
      uni.redirectTo({
        url: url,
      })
    } else if (types == 'ld'){
		//先验证是否登录
		if(apps.globalData.openUserInfo){
			//已经登录，直接跳转
			uni.redirectTo({
			  url: url,
			})
		}else{
			if(apps.globalData.appPlat == 'APP-PLUS' || apps.globalData.appPlat == 'H5'){
				//APP平台，跳转到登录页面
				uni.navigateTo({
					url: '/pages/Component/Module/Login/loginsms/login'
				});
			}else{
				//其他平台，直接跳转
				uni.redirectTo({
				  url: url
				})
			}
		}
	} else if (types == 's') {
      uni.switchTab({
        url: url
      })
    }
  } else {
    //带参数的跳转
    var param;
    var num = 0;
    for (var obj in data) {
      if (num == 0) {
        param = obj + '=' + data[obj];
      } else {
        param = param + '&' + obj + '=' + data[obj];
      }
      num++;
    }
    //进行跳转操作
    if (types == 'n') {
      uni.navigateTo({
        url: url + '?' + param
      })
    } else if (types == 'ln'){
		//先验证是否登录
		if(apps.globalData.openUserInfo){
			//已经登录，直接跳转
			uni.navigateTo({
			  url: url + '?' + param
			})
		}else{
			if(apps.globalData.appPlat == 'APP-PLUS' || apps.globalData.appPlat == 'H5'){
				//APP平台，跳转到登录页面
				uni.navigateTo({
					url: '/pages/Component/Module/Login/loginsms/login'
				});
			}else{
				//其他平台，直接跳转
				uni.navigateTo({
				  url: url + '?' + param
				})
			}
		}
	} else if (types == 'd') {
      uni.redirectTo({
        url: url + '?' + param
      })
    } else if (types == 'ld'){
		//先验证是否登录
		if(apps.globalData.openUserInfo){
			//已经登录，直接跳转
			uni.redirectTo({
			  url: url + '?' + param
			})
		}else{
			if(apps.globalData.appPlat == 'APP-PLUS' || apps.globalData.appPlat == 'H5'){
				//APP平台，跳转到登录页面
				uni.navigateTo({
					url: '/pages/Component/Module/Login/loginsms/login'
				});
			}else{
				//其他平台，直接跳转
				uni.redirectTo({
				  url: url + '?' + param
				})
			}
		}
	} else if (types == 's') {
      uni.switchTab({
        url: url + '?' + param
      })
    }
  }
}

function checkUserLogin(e, fn) {
  var that = this;
  var info = e.detail;
  //先判断用户是否已经登录
  if (apps.globalData.user_openinfo.avatarurl) {
    //表名用户已经登录了，直接抛出事件
    var res_data = {
      status: 'success'
    }
    fn(res_data);
  } else {
    //用户未登录，先登录
    getUserInfo(info, '', (res) => {
      //登录成功，抛出事件
      fn(res);
    })
  }
}
function getUserInfo(res, num, fn) {
  var that = this;
  var path = '/xyb/user_wechat/update';
  //判断用户是否同意授权
  if (res.rawData) {
    //判断是否有手机号登录
    if (num == '') {
      var data = {
        rawData: res.rawData,
        signature: res.signature,
        encryptedData: res.encryptedData,
        iv: res.iv
      }
    } else {
      var data = {
        rawData: res.rawData,
        signature: res.signature,
        encryptedData: res.encryptedData,
        iv: res.iv,
        phonum: num
      }
    }
    // data.men_code = apps.globalData.men_code;
    post(path, data, (res) => {
      uni.hideToast();
      if (res.data.code == 1) {
        //登录成功后的业务逻辑
        apps.globalData.user_openinfo = res.data.data.user_info;
        fn(res.data);
      } else {
        uni.showModal({
          title: '登陆失败',
          content: '服务器繁忙，请稍后重试！',
          showCancel: false
        })
      }
    })
  } else {
    fn({
      status: 'fail'
    });
  }
}

/*
*封装弹出框提示API组件，分别为showToast，showLoading，showModal；对应取值为t、l、m
*当为showToast时，types、content、title为必选，其他不选，其中title取值为s-success;l-loading
*当为showLoading时，只有types为必选，content为可选，其他不选，content为提示内容，不选默认显‘加载中’
*当为showModal时，types、content为必选，其他为可选，title默认值为‘提示’，fn返回用户选择结果，true为确定，false为取消
*duration默认为2000毫秒
*/
function toast(types, content, title, duration, fn) {
  title = title || '提示';
  duration = duration || 2000;
  content = content || '加载中';
  fn = fn || '';
  if (title == 's') {
    title = 'success';
  } else if (title == 'l') {
    title = 'loading';
  }
  //开始判断交互类型
  if (types == 't') {
    uni.showToast({
      title: content,
      icon: title,
      duration: duration
    })
  } else if (types == 'l') {
    uni.showLoading({
      title: content,
    })
  } else if (types == 'm') {
    if (fn == '') {
      //没有回调的modal
      uni.showModal({
        title: title,
        content: content,
        showCancel: true
      })
    } else {
      uni.showModal({
        title: title,
        content: content,
        success: function (res) {
          if (res.confirm) {
            fn(res.confirm);
          } else if (res.cancel) {
            fn(!(res.cancel));
          }
        }
      })
    }

  }

}
//判断登录状态并进入相应登录逻辑
function loginCheck(fn) {
  basic.loginCheck(apps, fn);
}
/*
*网络通讯ajax封装
*参数全部为必选参数
*path格式为：模块文件夹名/Wechat/控制器名/方法名，data为传递的数据对象
*fn为请求成功回调的方法
*/
function post(path, data, fn) {
  basic.post(apps, path, data, fn);
}
function gets(path, data, fn){
  basic.get(apps, path, data, fn);
}
function request(path, data, fn){
  basic.request(apps, path, data, fn);
}
function requestPost(path, data, fn){
  basic.requestPost(apps, path, data, fn);
}
/*
*网络上传图片到系统图库封装
*参数全部为必选参数
*user_id-上传图片的用户id
*file_name-图片名称
*file_path-图片临时路径
*/
function upimg(user_id, file_name, file_path, fn) {
  basic.upimg(apps, user_id, file_name, file_path, fn);
}

/*
*网络上传图库封装
*参数全部为必选参数
*path格式为：控制器名/方法名，data为传递的数据对象，默认不需要添加appkey等数据
*file_name文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
*file_path为文件的微信临时路径
*/
function upload(path, data, file_name, file_path, fn) {
  basic.up(apps, path, data, file_name, file_path, fn);
}

 /*封装微信支付接口
 *payment为后端传回的支付封装数据
 *fn为支付成功返回函数
 */
function payment(payment, mode, fn) {
		if(apps.globalData.appPlat == 'MP-WEIXIN'){
      
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: payment.pay.timeStamp,
				nonceStr:  payment.pay.nonceStr,
				package: payment.pay.package,
				signType: payment.pay.signType,
				paySign: payment.pay.paySign,
				success: function(res) {
					fn(res);
				},
				fail: function(res) {
					uni.hideLoading()
					uni.showModal({
						title: '支付失败',
						content: '支付失败，请您重试！',
						showCancel: false
					})
				}
			});
		}else{
			uni.requestPayment({
				provider: mode,
				orderInfo: payment.pay,
				success: function(res) {
					fn(res);
				},
				fail: function(res) {
					uni.hideLoading()
					uni.showModal({
						title: '支付失败',
						content: '支付失败，请您重试！',
						showCancel: false
					})
				}
			});
		}
}
/*************************/
/*****自写组件模块集成******/
/*************************/

/*
*图文混排模块封装函数
*/
function imgtext(content) {
  var mode1 = /<img(?:.|\s)*?src=("|')(.*?)("|')(?:.|\s)*?><br(?:.|\s)*?>/gi;
  var mode2 = /(<br(?:.|\s)*?>)+/gi;
  var mode3 = /<(?:.|\s)*?>/g;
  content = content.replace(mode1, "(imgpartsss)$2(imgpartsss)");
  content = content.replace(mode2, "\n");
  content = content.replace(mode3, "");
  var strs = new Array(); //定义一数组 
  strs = content.split("(imgpartsss)");
  var results = new Array();
  for (var i = 0; i < strs.length; i++) {
    if (i % 2 == 0) {
      if (trim(strs[i])) {
        var team = new Object();
        team.types = 'txt';
        team.info = trim(strs[i]);
        results.push(team);
      }
    } else {
      var team = new Object();
      team.types = 'pic';
      team.info = strs[i];
      results.push(team);
    }
  }
  return results;
}

function trim(str) {
  return str.replace(/(^\s*)|(\s*$)/g, "");
}

//常用匹配函数
function util(mode,info){
	if(mode == 'phone'){
		if(info){
			//判断是否为手机号
			var reg =/^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
			if(reg.test(info)){
				return true;
			}else{
				uni.showModal({
				    title: '手机号错误',
				    content: '请您正确填写11位手机号，再重新尝试！',
					showCancel:false
				});
				return false;
			}
		}else{
			uni.showModal({
			    title: '手机号为空',
			    content: '请先正确填写11位手机号，再重新尝试！',
				showCancel:false
			});
			return false;
		}
		
	}else if(mode == 'email'){
		if(info){
			//判断是否为手机号
			var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
			if(reg.test(info)){
				return true;
			}else{
				uni.showModal({
				    title: '邮箱格式错误',
				    content: '请您正确填写邮箱地址，再重新尝试！',
					showCancel:false
				});
				return false;
			}
		}else{
			uni.showModal({
			    title: '邮箱为空',
			    content: '请先正确填写邮箱格式，再重新尝试！',
				showCancel:false
			});
			return false;
		}
	}else if(mode == 'password'){
		if(info){
			//判断是否为手机号
			var reg = /^[0-9a-z_A-Z]+$/;
			if(reg.test(info)){
				return true;
			}else{
				uni.showModal({
				    title: '密码格式错误',
				    content: '密码必须由5~18位的数字、字母或下划线组成，请重新填写！',
					showCancel:false
				});
				return false;
			}
		}else{
			uni.showModal({
			    title: '密码为空',
			    content: '密码必须由5~18位的数字、字母或下划线组成！',
				showCancel:false
			});
			return false;
		}
	}
}

//接口工具类
module.exports.nav = nav;
module.exports.getNav = getNav;
module.exports.loginCheck = loginCheck;
module.exports.post = post;
module.exports.get = gets;
module.exports.request = request;
module.exports.requestPost = requestPost;
module.exports.up = upload;
module.exports.upimg = upimg;
module.exports.userlogin = checkUserLogin;
module.exports.userinfo = getUserInfo;
module.exports.toast = toast;
module.exports.pay = payment;
module.exports.path = getDirectPath;

//模块工具类
module.exports.txt = imgtext;

//交互工具类
// module.exports.sdk = sdk;
module.exports.goIndex = goIndexPage;

//基础工具类
module.exports.fix = floatFixed;
module.exports.numConvert = numConvert;
module.exports.timeAgo = timeAgo;
module.exports.locDis = locDis;
module.exports.util = util;



/*************************/
/*****系统基础库相关******/
/*************************/

//判断用户基础库版本是否满足要求

//返回首页方法
function goIndexPage() {
  var path = apps.globalData.appIndex;
  uni.switchTab({
    url: path
  })
}
//浮点数字转换通用方法
function floatFixed(num,fix){
  num = Number(num).toFixed(fix);
  num = Number(num);
  return num;
}
//数字转千、万格式显示
function numConvert(num) {
  var num = Number(num);
  if (num < 1000) {
    return num;
  } else if (num >= 1000 && num < 10000) {
    return (num / 1000).toFixed(1) + 'k';
  } else if (num >= 10000) {
    return (num / 10000).toFixed(2) + 'w';
  }
}

//时间日期转天时分
function timeAgo(savetime, mode) {
  var mode = mode || 'date';//date 为日期，time为时间戳
  if (mode == 'date') {
    savetime = savetime.replace('-','/');
    savetime = savetime.replace('-', '/');
    var data = new Date(savetime);
    var dateTimeStamp = Number(data.getTime());
  } else {
    var dateTimeStamp = Number(savetime * 1000);
  }

  var minute = 1000 * 60;      //把分，时，天，周，半个月，一个月用毫秒表示
  var hour = minute * 60;
  var day = hour * 24;
  var week = day * 7;
  var halfamonth = day * 15;
  var month = day * 30;
  var year = day * 365;
  var now = new Date().getTime();   //获取当前时间毫秒
  var diffValue = Number(now) - Number(dateTimeStamp);//时间差
  if (diffValue < 0) {
    return;
  }
  var minC = diffValue / minute;  //计算时间差的分，时，天，周，月
  var hourC = diffValue / hour;
  var dayC = diffValue / day;
  var weekC = diffValue / week;
  var monthC = diffValue / month;
  var yearC = diffValue / year;
  var result = '';
  if (yearC >= 1) {
    result = "" + parseInt(yearC) + "年前";
  } else if (monthC >= 1) {
    result = "" + parseInt(monthC) + "月前";
  } else if (weekC >= 1) {
    result = "" + parseInt(weekC) + "周前";
  } else if (dayC >= 1) {
    result = "" + parseInt(dayC) + "天前";
  } else if (hourC >= 1) {
    result = "" + parseInt(hourC) + "小时前";
  } else if (minC >= 1) {
    result = "" + parseInt(minC) + "分钟前";
  } else {
    result = "刚刚";
  }
  return result;
}
//计算两个经纬度之间的距离
function locDis(lat1, lng1, lat2, lng2){
	var radLat1 = lat1*Math.PI / 180.0;
	var radLat2 = lat2*Math.PI / 180.0;
	var a = radLat1 - radLat2;
	var b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
	s = s *6378.137 ;// EARTH_RADIUS;
	s = Math.round(s * 10000) / 10000;
	s = s.toFixed(2);
	return s;
}
/*************************/
/*****自定义组件事件******/
/*************************/

//自定义组件跳转的函数
function getDirectPath(e) {
  mod.modulePath(e);
}

